# -*- coding: utf-8 -*-
'''
Created on 2011-10-6

@author: y
'''

from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User


from cprt.accounts.models import UserDetail
from cprt.admin.models import Dept

class RegisterUserForm(ModelForm):
    
    username = forms.RegexField(max_length=30, label=u'用户名',regex=r'^[\w.@+-]+$',help_text=u'少于30个字符,只能包含字母、数字、"@/./+/-/_"')
    password1 = forms.CharField(max_length=30, label=u'登录口令',widget=forms.PasswordInput)
    password2 = forms.CharField(max_length=30, label=u'重复口令',widget=forms.PasswordInput, help_text=u'请重复输入确认上面的密码')
#    lastname = forms.CharField(max_length=4, label=u'姓')
#    firstname = forms.CharField(max_length=6, label=u'名')
    last_name = forms.CharField(max_length=30, label=u'真实姓名')
    email = forms.EmailField( label=u'电子邮箱' )

#    gender = forms.ChoiceField(label=u'性别',choices=)
#    birthday=forms.DateField(label=u'生日')
#    dept_id=forms.Select()
    
    class Meta:
        model = UserDetail
        exclude=('schedule_list','superior_auth_user','user')
        
    def clean_username(self):
        username = self.cleaned_data['username']
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(u'此用户名已经存在')
    
    def clean_password2(self):
        password1 = self.cleaned_data.get("password1", "")
        password2 = self.cleaned_data["password2"]
        if password1 != password2:
            raise forms.ValidationError(u"输入的两个密码不匹配")
        return password2
    
    def save(self, commit=True):
        user = User.objects.create_user(self.cleaned_data['username'], self.cleaned_data['email'], self.cleaned_data['password2'])
        user.last_name=self.cleaned_data['last_name']
        user.save()
        user_detail = UserDetail(gender=self.cleaned_data['gender'],title=self.cleaned_data['title'],birthday=self.cleaned_data['birthday'],dept=self.cleaned_data['dept'])
        user_detail.user=user;
        user_detail.superior_auth_user_id=self.cleaned_data['dept'].principal_auth_user_id
        user_detail.save()
        return user_detail
